app.controller("systemConfigCtrl", function ($scope, systemConfigService, $log) {
    $log.info('SystemConfigController initialize');

    var CONFIG_BGS = "bgs";

    var CONFIG_DATABASE = "database";

    var CONFIG_MQ = "mq";

    var CONFIG_APP_UPLOAD = "appUpload";

    var CONFIG_AIR_INFO = "airInfo";

    var CONFIG_MSG_UP_CENTER = "msgUpCenter";

    var CONFIG_WEBSITE = "website";

    var CONFIG_FORWARDER = "forwarder";

    var IGNORE_ALARM = "ignoreAlarm";

    var  ROLE_DISABLE ="roleDisable";


    /**
     * 页面初始化
     */
    $scope.init = function () {
        // 默认展示bgs系统配置
        $scope.showFlag = CONFIG_BGS;

        // 获取系统配置
        $scope.showConfig(CONFIG_BGS);
    };

    /**
     * 点击禁止普通用户重启复选框
     */
    $scope.clickSubscribe = function () {
        var checkbox = document.getElementById('subscribe');

        if (checkbox.checked) {
            $scope.roleDisable.roleDisable="true"
        } else {
            $scope.roleDisable.roleDisable="false"
        }
    }


    /**
     * 保存联系人和处理方法信息（弹窗里的数据）
     * @param configType
     */
    $scope.clickSave = function () {
        // $('#exampleModal').modal('show')
        $scope.saveConfig($scope.showFlag, $scope.targetDialog);
    }


    /**
     * 展示配置项
     * @param configType
     */
    $scope.showConfig = function (configType) {
        $scope.showFlag = configType;
        // 参数
        var action = {
            action: "getSystemConfig",
            configType: configType
        };
        $.fn.jqLoading({height: 80, width: 240, text: "正在加载中，请耐心等待...."});
        systemConfigService.getSystemConfig(action, function (data) {
             $.fn.jqLoading("destroy");
            if (data.status === "SUCCESS") {
                if (!isNullOrEmpty(data.data.config)) {
                    $log.info(data.data.config);
                    $scope.targetDialog = data.data.config;
                    switch (configType) {
                        case CONFIG_BGS:
                            $scope.bgsConfig = data.data.config;
                            break;
                        case CONFIG_DATABASE:
                            $scope.databaseConfig = data.data.config;
                            break;
                        case CONFIG_MQ:
                            $scope.mqConfig = data.data.config;
                            break;
                        case CONFIG_APP_UPLOAD:
                            $scope.appUploadConfig = data.data.config;
                            break;
                        case CONFIG_AIR_INFO:
                            $scope.airInfoConfig = data.data.config;
                            msgAlarmList = data.data.config.msgAlarm;
                            break;
                        case CONFIG_MSG_UP_CENTER:
                            $scope.msgUpCenterConfig = data.data.config;
                            break;
                        case CONFIG_WEBSITE:
                            $scope.websiteConfig = data.data.config;
                            break;
                        case CONFIG_FORWARDER:
                            $scope.forwarderConfig = data.data.config;
                            break;
                        case IGNORE_ALARM:
                            $scope.ignoreAlarm = data.data.config;
                            break;
                        case ROLE_DISABLE:
                            $scope.roleDisable = data.data.config;
                            var checkbox = document.getElementById('subscribe');
                            checkbox.checked=$scope.roleDisable.roleDisable=="true"?true:false
                            break;
                        default:
                            break;
                    }
                }
            } else {
                message_alert('提示', data.errorReason, null);
            }
        }, function () {
            $.fn.jqLoading("destroy");
        });

    };


    /**
     * 保存系统配置
     * @param systemConfig
     */
    $scope.saveConfig = function (configType, configMap) {
        // 弹出确认框
        message_confirm("提示", "是否保存当前配置？", function (result) {
            if (result) {
                // action
                var action = {
                    action: "saveSystemConfig",
                    configType: configType
                };

                systemConfigService.saveSystemConfig(action, configMap, function (data) {
                    if (data.status === 'SUCCESS') {
                        message_alert('提示', '保存成功', function () {
                            $scope.showConfig(configType);
                        });
                    } else {
                        message_alert('提示', data.errorReason, null);
                    }
                });
            }
        });

    };



    /**
     * 忽略告警配置项页面点击转移
     */
    $scope.transferItemsRight= function (sourceId, targetId) {
        var source = document.getElementById(sourceId);
        var selectedItems = source.getElementsByClassName('selected');
        if (selectedItems.length === 0) {
            alert('请先选择要穿梭的项！');
            return;
        }
        while (selectedItems.length > 0) {
            var item = selectedItems[0];
            item.classList.remove('selected'); // 移除选中状态
            // 使用 filter 方法获取所有 name 属性等于 123 的对象
            var filteredArray = $scope.ignoreAlarm.alarm.filter(function (obj) {
                return obj.id ==item.getAttribute('name');
            });

            // 在原数组中删除所有 name 属性等于 123 的对象
            for (var i = $scope.ignoreAlarm.alarm.length - 1; i >= 0; i--) {
                if ($scope.ignoreAlarm.alarm[i].id == item.getAttribute('name')) {
                    $scope.ignoreAlarm.alarm.splice(i, 1);
                }
            }

            $scope.ignoreAlarm.ignore=[...$scope.ignoreAlarm.ignore,...filteredArray]
            //   target.appendChild(item);
        }
        checkButtonsState();
    }

    /**
     * 忽略告警配置项页面点击转移
     */
    $scope.transferItemsLeft = function (sourceId, targetId) {
        var source = document.getElementById(sourceId);
        var selectedItems = source.getElementsByClassName('selected');
        if (selectedItems.length === 0) {
            alert('请先选择要穿梭的项！');
            return;
        }
        while (selectedItems.length > 0) {
            var item = selectedItems[0];
            item.classList.remove('selected'); // 移除选中状态
            // 使用 filter 方法获取所有 name 属性等于 目标 的对象
            var filteredArray = $scope.ignoreAlarm.ignore.filter(function (obj) {
                return obj.id ==item.getAttribute('name');
            });

            // 在原数组中删除所有 name 属性等于 目标 的对象
            for (var i = $scope.ignoreAlarm.ignore.length - 1; i >= 0; i--) {
                if ($scope.ignoreAlarm.ignore[i].id == item.getAttribute('name')) {
                    $scope.ignoreAlarm.ignore.splice(i, 1);
                }
            }

            $scope.ignoreAlarm.alarm=[...$scope.ignoreAlarm.alarm,...filteredArray]
        }
        checkButtonsState();
    }

    /**
     * 改变菜单样式
     */
    $scope.changeMenu = function () {
        $(event.target).parent().addClass("active");
        $(event.target).parent().siblings().removeClass("active");
    };

    /**
     * 构建航信接口配置
     */
    $scope.buildAirInfoConfig = function (airInfoConfig) {
        var msgAlarmList = [];
        var list = $(".msgAlarmContent").children("td.config-content");
        for (var i = 0; i < list.length; i++) {
            var name = $(list[i]).children("input[name='name']").val();
            var startTime = $(list[i]).children("input[name='startTime']").val();
            var endTime = $(list[i]).children("input[name='endTime']").val();
            var timeout = $(list[i]).children("input[name='timeout']").val();
            var msgAlarm = {
                name: name,
                startTime: startTime,
                endTime: endTime,
                timeout: timeout
            };
            msgAlarmList.push(msgAlarm);
        }
        if (msgAlarmList.length > 0) {
            airInfoConfig["msgAlarm"] = msgAlarmList;
        }
        return airInfoConfig;
    };

    // 航信接口中报文告警配置无效标识
    $scope.msgAlarmInvalid = false;

});

// 全局变量 报文告警list
var msgAlarmList = new Array();

// 全局变量 angular的$scope作用域
var $scope = null;

// 加载完页面后，给$scope赋值
window.onload = function () {
    //获取ng-controller元素
    var element = document.querySelector('[ng-controller=systemConfigCtrl]');
    //获取$scope变量
    $scope = angular.element(element).scope();
};

/**
 * 开始时间change事件
 * @param obj
 */
function changeStartTime(obj) {
    var startTimeObj = $(obj);
    // var endTimeObj = $(obj).next();
    var prevEndTimeObj;
    // var prevStartTimeObj;
    for (var i = 1; i <= msgAlarmList.length; i++) {
        if (startTimeObj.attr('id') === ('startTime' + i)) {
            var prevEndTimeId = 'endTime';
            // var prevStartTimeId = 'startTime';
            if (i === 1) {
                prevEndTimeId = prevEndTimeId + msgAlarmList.length;
                // prevStartTimeId = prevStartTimeId + msgAlarmList.length;
            } else {
                prevEndTimeId = prevEndTimeId + (i - 1);
                // prevStartTimeId = prevStartTimeId + (i -1);
            }
            prevEndTimeObj = $('#' + prevEndTimeId);
            // prevStartTimeObj = $('#' + prevStartTimeId);

            // var endTimeVal = endTimeObj.val();
            // var prevStartTimeVal = prevStartTimeObj.val();
            // if(endTimeVal >= prevStartTimeVal){
            //     startTimeObj.attr('min', prevStartTimeVal);
            //     startTimeObj.attr('max', endTimeVal);
            // }else{
            //     startTimeObj.attr('min', endTimeVal);
            //     startTimeObj.attr('max', prevStartTimeVal);
            // }

            var startTimeVal = startTimeObj.val();

            prevEndTimeObj.val(startTimeVal);
            break;
        }
    }
}

/**
 * 结束时间change事件
 * @param obj
 */
function changeEndTime(obj) {
    var endTimeObj = $(obj);
    // var startTimeObj = $(obj).prev();
    var nextStartTimeObj;
    // var nextEndTimeObj;
    for (var i = 1; i <= msgAlarmList.length; i++) {
        if (endTimeObj.attr('id') === ('endTime' + i)) {
            var nextStartTimeId = 'startTime';
            // var nextEndTimeId = 'endTime';
            if (i === msgAlarmList.length) {
                nextStartTimeId = nextStartTimeId + 1;
                // nextEndTimeId = nextEndTimeId + 1;
            } else {
                nextStartTimeId = nextStartTimeId + (i + 1);
                // nextEndTimeId = nextEndTimeId + (i + 1);
            }
            nextStartTimeObj = $('#' + nextStartTimeId);
            // nextEndTimeObj = $('#' + nextEndTimeId);

            // var startTimeVal = startTimeObj.val();
            // var nextEndTimeVal = nextEndTimeObj.val();
            // if(startTimeVal <= nextEndTimeVal){
            //     endTimeObj.attr('min', startTimeVal);
            //     endTimeObj.attr('max', nextEndTimeVal);
            // }else{
            //     endTimeObj.attr('min', nextEndTimeVal);
            //     endTimeObj.attr('max', startTimeVal);
            // }

            var endTimeVal = endTimeObj.val();
            nextStartTimeObj.val(endTimeVal);
            break;
        }
    }
}

/**
 * 超时事件触发事件
 * @param obj
 */
function changeTimeout(obj) {
    var timeoutObj = $(obj);
    for (var i = 1; i <= msgAlarmList.length; i++) {
        if (timeoutObj.attr('id') === ('timeout' + i)) {
            if (isNullOrEmpty(timeoutObj.val())) {
                $('#timeoutError' + i).html('时间阀值不能为空');
                $scope.msgAlarmInvalid = true;
            } else if (timeoutObj.val().length > 3) {
                $('#timeoutError' + i).html('最大长度3');
                $scope.msgAlarmInvalid = true;
            } else {
                $('#timeoutError' + i).html('');
                $scope.msgAlarmInvalid = false;
            }
            $scope.$apply();
            break;
        }
    }
}




